#coding:utf-8
from __future__ import unicode_literals
import time
import os,shutil

from django.shortcuts import render,HttpResponse,render_to_response,get_object_or_404
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect,Http404
from django.urls import reverse
from django.template import RequestContext

from deploy.saltapi import SaltAPI
from oms import settings
from oms import  settings_local
from oms.models import *
from oms.mysql import db_operate
from asset.models import HostList
from deploy.code import Code_Work
from json_data import BuildJson
from deploy.form import ContactForm
from .login_ssh import *
import paramiko


# Create your views here.

################

#以下是编译操作
def module_deploy(request):
    """
    编译操作
    """
    ret = '编译请看编译日志，最后编译返回结果请看这里 (编译过程会比较慢，页面会呈现出刷新状态，不用慌张 请耐心等待......)'
    tgt='localhost'

    f = open('java_hard.txt', 'r')
    ver_all = []
    module = set()
    for i in file.xreadlines(f):
        if not i.startswith('#'):  # 过滤'#' 开头的注释
            ii = i.strip().replace("\n", "")  # 去掉两边空格和换行符
            v = ii.split('|')[0]
            ver_all.append(ii)
            module.add(v)

    while '' in ver_all:  # 列表去除空元素
        ver_all.remove('')

    f.close()

    if request.method == 'POST':
        ver = request.POST.get('version')
        mo = ver.split('|')[0]
        env = ver.split('|')[2]
        print "进行编译...."
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname, username=username, password=password)
        stdin, stdout, stderr = ssh.exec_command("cd /media && source /etc/profile && bash update_hard_java.sh {0} {1}".format(mo,env))
        ret = stdout.read()
        print ret

    return render_to_response('salt/salt_module_by.html',{'ret':ret,'tgt':tgt,'ver_all':ver_all})


#### 以下是发布功能操作
def module_fabu(request):
    """
    发布操作
    """
    ret = '发布结果请看这里.............'
    tgt='localhost'

    f = open('java_hard.txt', 'r')
    ver_all = []
    module = set()
    for i in file.xreadlines(f):
        if not i.startswith('#'):  # 过滤'#' 开头的注释
            ii = i.strip().replace("\n", "")  # 去掉两边空格和换行符
            v = ii.split('|')[0]
            ver_all.append(ii)
            module.add(v)

    while '' in ver_all:  # 列表去除空元素
        ver_all.remove('')

    try:
        module.remove("")
    except KeyError:
        pass

    f.close()

    if request.method == 'POST':
        fbmk = request.POST.get('fbmk')
        env = request.POST.get('env')
        # print fbmk
        # print env
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname, username=username, password=password)
        stdin, stdout, stderr = ssh.exec_command("cd /srv/salt/source/java && bash update_hard_{0}.sh {1}".format(env,fbmk))
        ret = stdout.read()
        print "进行发布...."

    return render_to_response('salt/salt_module_fabu.html',{'ret':ret,'tgt':tgt,'module':module})


######################## 版本号修改###########
def change_ver(request):
    module = set()
    with open('java_hard.txt', 'r') as f:
        for line in f.xreadlines():
            if not line.startswith('#'):
                ii = line.strip().replace("\n", "")
                v = ii.split('|')[0]
                module.add(v)
            try:
                module.remove("")
            except KeyError:
                pass

    if request.method == 'POST':
        module=request.POST.get('module')
        ver=request.POST.get('ver')
        env=request.POST.get('env')   # 都能正常获取到值
        new_l = module + '|' + ver + '|' + env

        form = ContactForm(request.POST)                 # 验证表单必须要同时有值
        if form.is_valid():
            # print module
            # print ver
############修改文件#############
            # 删除行
            with open('java_hard.txt', 'r') as f:
                lines = f.readlines()
                # print (lines)

            with open('java_hard.txt', 'w') as f_w:
                for line in lines:
                    if module in line and env in line:
                        continue
                    f_w.write(line)

            # 追加行
            with open('java_hard.txt', 'a') as f_a:
                f_a.write('\n')
                f_a.write(new_l)
##################################################
            return HttpResponseRedirect(reverse('deploy:module_deploy'))
        else:
            return render(request, "salt/change_ver.html", {"error": form.errors,"form":form})  # 表单不填写就提示报错信息

    return render_to_response('salt/change_ver.html',{'module':module})





########################################### 代码发布功能################################
def code_deploy(request):
    """
    Pull code for building, pushed to the server
    """

    ret = '此功能尚不对外开放......'
    host = {'ga': 'test-01', 'beta': 'localhost.localdomain'}
    user = request.user
    if request.method == 'POST':
        action = request.get_full_path().split('=')[1]
        if action == 'push':
            pro = request.POST.get('project')
            url = request.POST.get('url')
            ver = request.POST.get('version')
            env = request.POST.get('env')
            capi = Code_Work(pro=pro, url=url, ver=ver)
            data = {pro: {'ver': ver}}
            obj = capi.work()                               # 构建rpm包
            if obj['comment'][0]['result'] and obj['comment'][1]['result'] and obj['comment'][2]['result']:
                json_api = BuildJson()
                json_api.build_data(host[env], data)        # 刷新pillar数据，通过deploy下发SLS执行代码发布
                sapi = SaltAPI(url=settings.SALT_API['url'], username=settings.SALT_API['user'],
                               password=settings.SALT_API['password'])
                if env == 'beta':
                    jid = sapi.target_deploy('beta', 'deploy.' + pro)
                elif env == 'ga':
                    jid = sapi.target_deploy('tg', 'deploy.' + pro)
                else:
                    jid = sapi.target_deploy('beta', 'deploy.' + pro)
                time.sleep(8)
                db = db_operate()
                sql = 'select returns from salt_returns where jid=%s'
                ret = db.select_table(settings.RETURNS_MYSQL, sql, str(jid))  # 通过jid获取执行结果
    return render_to_response('salt/code_deploy.html',{'ret': ret})